<template>
  <vc-viewer
    class="viewer"
    :animation="animation"
    :logo="false"
    :infoBox="false"
    ref="viewer"
    :scene3DOnly="true"
    :shouldAnimate="true"
    @ready="ready"
    @LEFT_CLICK="LEFT_CLICK"
  >
    <wall :attributes="attributes" :positions="positions" :vertex-format="vertexFormat" :appearance="appearance"></wall>
    <plane :attributes="attributes" :vertex-format="vertexFormat" :appearance="appearance" :modelMatrix="modelMatrix"></plane>

    <vc-layer-imagery ref="layerText">
      <vc-provider-imagery-tianditu
        :protocol="protocol"
        :mapStyle="mapStyle"
        token="436ce7e50d27eede2f2929307e6b33c0"
      >
      </vc-provider-imagery-tianditu>
    </vc-layer-imagery>
    <!--    <vc-layer-imagery>-->
    <!--      <vc-provider-imagery-openstreetmap></vc-provider-imagery-openstreetmap>-->
    <!--    </vc-layer-imagery>-->
  </vc-viewer>
</template>
<script>
  import Wall from './widget/wall'
  import Plane from './widget/plane'

  export default {
  data() {
    return {
      mapStyle: 'img_w', // 天地影像图类型
      protocol: 'http', // 天地图请求协议类型
      animation: true,
      timeline: true,
      appearance: null,
      geometry: null,
      attributes: null,
      vertexFormat: null,
      cesiumInstance: null,
      modelMatrix: null,
      entities: {
        task: {},
        sources: {},
        event: {},
        command: {}
      },
      positions: [
        { lng: 117.191245, lat: 31.803946, height: 100000.0 },
        { lng: 116.191245, lat: 31.803946, height: 100000.0 },
        { lng: 116.191245, lat: 29.803946, height: 100000.0 },
        { lng: 117.191245, lat: 29.803946, height: 100000.0 },
        { lng: 117.191245, lat: 31.803946, height: 100000.0 }
      ],
      images: {
        peopleType1: require('@/assets/gis/peopleType1.svg'), // 人员
          peopleType2: require('@/assets/gis/peopleType2.svg'), // 人员
          position: require('@/assets/gis/options_select.svg'), // 定位
      } // 图标icon
    };
  },
  components: {
    Wall,
    Plane
  },
  mounted() {
  },
  methods: {
    LEFT_CLICK(movement) {
      this.getCurrentView();
      this.getPosition(movement);
      const _this = this;
      if (this.timer) clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        const { viewer } = _this.cesiumInstance;
        console.log("movement",movement)
        const feature = viewer.scene.pick(movement.position);
        console.log(feature);
        // feature.id：选中的地图覆盖物不一样，id表示的对象也不同，可能为覆盖物的id，也可能为覆盖物本身
        if (feature && feature.id && feature.id.type) {
          let entity = _this.entities[feature.id.type][feature.id.id];
          if (entity) {
            _this.focusOn(feature.id);
          }
        }
      }, 200);
    },
    //获取当前摄像头数据
    getCurrentView() {
      // 获取当前视角的地图数据
      const { viewer } = this.cesiumInstance;
      const obj = {
        location:
          viewer.camera.position.x +
          "," +
          viewer.camera.position.y +
          "," +
          viewer.camera.position.z,
        heading: viewer.camera.heading,
        pitch: viewer.camera.pitch,
        roll: viewer.camera.roll,
      };
      console.log(obj, "sss");
    },
    //聚焦弹窗
    focusOn(feature) {
      const { viewer } = this.cesiumInstance
      // viewer.flyTo(this.entities[feature.type][feature.id], { duration: 2.0 })
      //触发回到函数
      // this.$emit('showLayer', feature)
      console.log("feature",feature)
    },
    getPosition(movement) {
      // 获取并绘制点位
      const { Cesium, viewer } = this.cesiumInstance;
      const ellipsoid = viewer.scene.globe.ellipsoid;
      let cartesian = viewer.camera.pickEllipsoid(movement.position, ellipsoid);
      if (cartesian) {
        //将笛卡尔坐标转换为地理坐标
        let cartographic = ellipsoid.cartesianToCartographic(cartesian);
        //将弧度转为度的十进制度表示
        let longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
        let latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
        console.log(longitudeString, latitudeString, "ssss");
      }
    },
    // 地形数据
    showDemModel() {
      const { Cesium, viewer } = this.cesiumInstance;
      let terrainProvider = new Cesium.CesiumTerrainProvider({
        url: 'http://124.71.201.3:8017/hs'
      });
      viewer.terrainProvider = terrainProvider;
    },
    // 实例信息
    showBillboard(dataSource, info) {
      const { Cesium, viewer } = this.cesiumInstance;
      dataSource.map((item, index) => {
        const _entityId = info + '---' + item.key;
        let entityInfo = {
          id: _entityId,
          position: Cesium.Cartesian3.fromDegrees(
            item.location.lng,
            item.location.lat,
            5
          ),
          type: info,
          billboard: {
            image: this.images[item.gisIcon],
            show: true,
            scale: item.scale || 1,
            distanceDisplayCondition: { near: 0, far: 1000000 }, // 距离镜头多远的距离将不显示
            // scaleByDistance: { near: 10, nearValue: 0.7, far: 2000, farValue: 1 },//根据距离镜头的距离等比例缩放图标大小
            disableDepthTestDistance: 1000000 // 设置图标的显示不会被覆盖
          },
          label: {
            text: item.title,
            font: 'normal 30px Monospace',
            scale: 0.5,
            showBackground: true,
            fillColor: Cesium.Color.WHITE,
            backgroundColor: Cesium.Color.BLACK.withAlpha(0.4),
            backgroundPadding: Cesium.Cartesian2(7, 5),
            pixelOffset: { x: 0.0, y: -40 },
            distanceDisplayCondition: { near: 0, far: 1000000 }, // 距离镜头多远的距离将不显示
            disableDepthTestDistance: 1000000, // 设置标签的显示不会被覆盖
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // 左对齐
            verticalOrigin: 0 // 垂直居中
          }
        };
        if (!this.entities[info][_entityId]) {
          console.log(2);
          let entity = viewer.entities.add(entityInfo);
          this.entities[info][_entityId] = entity;
        }
      });
    },
    // 划平面
    writePlane(Cartesian3, Matrix4, Transforms) {
      const dimensions = new Cartesian3(400000.0, 300000.0, 1.0)
      const translateMatrix = Transforms.eastNorthUpToFixedFrame(Cartesian3.fromDegrees(117.191245, 31.803946))
      const scaleMatrix = Matrix4.fromScale(dimensions)
      const planeModelMatrix = new Matrix4()
      this.modelMatrix = Matrix4.multiply(translateMatrix, scaleMatrix, planeModelMatrix)
    },
    ready(cesiumInstance) {
      this.cesiumInstance = cesiumInstance;
      const { Cesium, viewer } = cesiumInstance;
      const { PerInstanceColorAppearance, ColorGeometryInstanceAttribute, Cartesian3, Matrix4, Transforms } = Cesium
      this.appearance = new PerInstanceColorAppearance({
        flat: true
      })
      this.vertexFormat = PerInstanceColorAppearance.FLAT_VERTEX_FORMAT
      this.appearanceOutline = new PerInstanceColorAppearance({
        flat: true,
        renderState: {
          lineWidth: Math.min(2.0, viewer.scene.maximumAliasedLineWidth)
        }
      })
      this.attributes = {
        color: new ColorGeometryInstanceAttribute(Math.random(), Math.random(), Math.random(), 0.5)
      }
      // 平面图形
      this.writePlane(Cartesian3, Matrix4, Transforms)
      // 不显示动画控件
      viewer.animation.container.style.visibility = 'hidden';
      viewer.scene.requestRenderMode = true;
      viewer.scene.globe.depthTestAgainstTerrain = true;
      // 隐藏背景图
      console.log(viewer.scene);
      // 取消双击事件
      viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
      );
      viewer.camera.flyTo({
        destination: new Cesium.Cartesian3.fromDegrees(
            117.191245, 31.803946, 1000
        ),
        orientation: {
          heading: 5.967795163860433,
          pitch: -0.9511768596472026,
          roll: 6.281919108740777
        }
      });
      this.showDemModel();
    }
  }

};
</script>
<style>
.viewer {
  width: 100%;
  height: 400px;
}
</style>
